"""日志模块"""
import logging
import logging.config
import os
from logging import DEBUG, ERROR, FATAL, INFO, NOTSET, WARN

LEVEL_COLOR = {
    DEBUG: "\33[2;39m",
    INFO: "\33[0;36m",
    WARN: "\33[0;33m",
    ERROR: "\33[0;35m",
    FATAL: "\33[1;31m",
    NOTSET: "",
}


class ScreenHandler(logging.StreamHandler):
    """重新定义控制台输出日志控制器"""

    def emit(self, record):
        try:
            msg = self.format(record)
            stream = self.stream
            fs = LEVEL_COLOR[record.levelno] + "%s\n" + "\33[0m"
            stream.write(fs % msg)
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)


logging.ScreenHandler = ScreenHandler


def init_log(file_path, web_mode="production"):
    """加载log配置"""
    log_level = "DEBUG"
    handlers = ["console"]
    if web_mode == "production":
        log_level = "INFO"
    conf = {
        "version": 1,
        "formatters": {
            "standard_format": {
                "format": "%(asctime)s %(process)d,%(threadName)s %(filename)s:%(lineno)d"
                " |%(name)s| [%(levelname)s] %(message)s"
            }
        },
        "handlers": {
            "console": {
                "class": "logging.ScreenHandler",
                "formatter": "standard_format",
                "level": "DEBUG",
                "stream": "ext://sys.stdout",
            }
        },
        "loggers": {},
        "root": {"level": log_level, "handlers": handlers},
    }
    logging.config.dictConfig(conf)
    log_obj = logging.getLogger()
    return log_obj


def test1():
    init_log(
        "/home/common/yth/code/hebei_gate/websvr/gate/src/web_flask/common"
    )
    log = logging.getLogger()
    for i in range(0, 10):
        log.debug("debug ... %d", i)
        log.info("info ... %d", i)
        log.warning("warning ... %d", i)
        log.error("error ... %d", i)
        log.fatal("fatal ... %d", i)


if __name__ == "__main__":
    test1()
